<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>新增Token</title>
    <link rel="stylesheet" href="../../../component/pear/css/pear.css" />
</head>

<body>
    <form class="layui-form" action="">
        <div class="mainBox">
            <div class="main-container">
                <div class="layui-form-item">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required" autocomplete="off"
                            placeholder="请输入Token名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">允许IP</label>
                    <div class="layui-input-block">
                        <textarea name="allowed_ips" id="allowed_ips" placeholder="请输入允许IP（多个用逗号分隔，*表示所有）"
                            lay-verify="verifyIP" class="layui-textarea">*</textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">用途说明</label>
                    <div class="layui-input-block">
                        <textarea name="description" id="description" placeholder="请输入Token用途说明"
                            class="layui-textarea"></textarea>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">过期时间</label>
                    <div class="layui-input-block">
                        <input type="text" name="expires_time" id="expires_time" autocomplete="off"
                            placeholder="请选择过期时间" class="layui-input" readonly>
                        <div class="layui-form-mid layui-word-aux">默认100年</div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block">
                        <input type="radio" name="is_active" value="1" title="启用" lay-skin="tag" checked>
                        <input type="radio" name="is_active" value="0" title="禁用" lay-skin="tag">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">排序号</label>
                    <div class="layui-input-block">
                        <input type="text" name="sort_num" id="sort_num" lay-verify="verifySort" autocomplete="off"
                            value="0" placeholder="请输入排序号" class="layui-input">
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="token-save">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="reset" class="pear-btn pear-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </div>
    </form>

    <script src="../../../component/com/api.js"></script>
    <script src="../../../component/com/auth.js"></script>
    <script src="../../../component/layui/layui.js"></script>
    <script src="../../../component/pear/pear.js"></script>
    <script>
        layui.use(['form', 'jquery', 'laydate'], function () {
            let form = layui.form;
            let $ = layui.jquery;
            let laydate = layui.laydate;
            let API_BASE_URL = apiConfig.baseUrl;
            let token = window.localStorage.getItem("token") || window.sessionStorage.getItem("token");

            // 初始化日期时间选择器
            laydate.render({
                elem: '#expires_time',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                value: new Date(Date.now() + 100 * 365 * 24 * 60 * 60 * 1000), // 默认100年后
                min: new Date().getTime(), // 不能选择过去的时间
                btns: ['clear', 'confirm'],
                theme: '#1E9FFF'
            });


            // 自定义验证规则
            form.verify({
                verifySort: function (value) {
                    if (!/^\d+$/.test(value)) {
                        return "排序号必须为正整数！";
                    }
                    if (parseInt(value) < 0) {
                        return "排序号不能为负数！";
                    }
                },
                verifyIP: function (value) {
                    if (value === "*") return;  // 允许通配符

                    const ips = value.split(',');
                    const ipReg = /^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$/;

                    // 检查每个IP
                    for (let ip of ips) {
                        ip = ip.trim();
                        if (!ip) return "IP地址不能为空！";
                        if (!ipReg.test(ip)) return `无效的IP地址: ${ip}`;
                    }

                    // 额外检查：不允许单个数字
                    if (/^\d+$/.test(value)) {
                        return "请输入完整的IP地址（如 192.168.1.1）";
                    }
                }
            });

            // 提交表单
            form.on('submit(token-save)', function (data) {
                // 处理过期时间格式（如果需要转换为后端接受的格式）
                if (data.field.expires_time) {
                    // 将前端显示的格式转换为后端需要的格式
                    const date = new Date(data.field.expires_time);
                    data.field.expires_time = date.toISOString(); // 或者保持原格式，根据后端要求调整
                }

                $.ajax({
                    url: `${API_BASE_URL}/common/token/`,
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'POST',
                    headers: {
                        "Authorization": token
                    },
                    success: function (result) {
                        if (result.code == 200) {
                            layer.msg(result.message, {
                                icon: 1,
                                time: 1000
                            }, function () {
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                                parent.layui.table.reload("base-table");
                            });
                        } else {
                            let errorMsg = result.message;
                            if (result.data && typeof result.data === 'object') {
                                const firstError = Object.values(result.data)[0];
                                if (firstError) errorMsg = firstError[0];
                            }
                            layer.msg(errorMsg, { icon: 2, time: 2000 });
                        }
                    },
                    error: function (xhr) {
                        layer.msg("请求失败: " + xhr.statusText, { icon: 2 });
                    }
                });
                return false;
            });
        });
    </script>
</body>

</html>